package io.zhengsh.vvip.leetcode.twopointer;

import java.util.Arrays;

public class Q977_SquaresOfASortedArray {

    class Solution {

        // 直接排序解法
        public int[] sortedSquares1(int[] nums) {
            int[] arr = new int[nums.length];
            for (int i = 0; i < nums.length; i++) {
                arr[i] = nums[i] * nums[i];
            }
            Arrays.sort(arr);
            return arr;
        }

        public int[] sortedSquares(int[] nums) {
            int len = nums.length;
            int nagative = -1;
            for (int i = 0; i < len; i++) {
                if (nums[i] < 0) {
                    nagative = i;
                } else {
                    break;
                }
            }
            int[] res = new int[len];
            int index = 0, i = nagative, j = nagative + 1;
            while (i >= 0 || j < len) {
                if (i < 0) {
                    res[index] = nums[j] * nums[j];
                    j++;
                } else if (j == len) {
                    res[index] = nums[i] * nums[i];
                    i--;
                } else if (nums[i] * nums[i] < nums[j] * nums[j]) {
                    res[index] = nums[i] * nums[i];
                    i--;
                } else {
                    res[index] = nums[j] * nums[j];
                    j++;
                }
                index++;
            }
            return res;
        }
    }
}
